package com.atguigu.chapter08;

import com.atguigu.bean.HotItem;
import com.atguigu.bean.UserBehavior;
import com.atguigu.util.AtguiguUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Date;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/21 14:17
 */
public class Flink03_High_Project_TopN {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        
        env
            .readTextFile("input/UserBehavior.csv")
            .map(line -> { // 对数据切割, 然后封装到POJO中
                String[] split = line.split(",");
                return new UserBehavior(Long.valueOf(split[0]), Long.valueOf(split[1]), Integer.valueOf(split[2]), split[3], Long.parseLong(split[4]) * 1000);
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                    .withTimestampAssigner((element, recordTimestamp) -> element.getTimestamp())
            )
            .filter(behavior -> "pv".equals(behavior.getBehavior()))
            .keyBy(UserBehavior::getItemId)
            .window(SlidingEventTimeWindows.of(Time.hours(1), Time.minutes(20)))
            .aggregate(
                new AggregateFunction<UserBehavior, Long, Long>() {
                    @Override
                    public Long createAccumulator() {
                        return 0L;
                    }
                    
                    @Override
                    public Long add(UserBehavior value, Long acc) {
                        return acc + 1;
                    }
                    
                    @Override
                    public Long getResult(Long acc) {
                        return acc;
                    }
                    
                    @Override
                    public Long merge(Long a, Long b) {
                        return null;
                    }
                },
                // 商品id 窗口结束时间 点击量
                new ProcessWindowFunction<Long, HotItem, Long, TimeWindow>() {
                    @Override
                    public void process(Long key,
                                        Context ctx,
                                        Iterable<Long> elements,
                                        Collector<HotItem> out) throws Exception {
                        out.collect(new HotItem(key, elements.iterator().next(), ctx.window().getEnd()));
                    }
                }
            )
            .keyBy(HotItem::getWindowEnd)
            .process(new KeyedProcessFunction<Long, HotItem, String>() {
                
                private ListState<HotItem> hotItemListState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    hotItemListState = getRuntimeContext()
                        .getListState(new ListStateDescriptor<HotItem>("hotItemListState", HotItem.class));
                    
                }
                
                @Override
                public void processElement(HotItem hotItem,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    // 每来一条数据, 把这条数据存入到一个状态, 等所有的都来齐了, 则让定时器去计算topN
                    Iterable<HotItem> hotItems = hotItemListState.get();
                    // 如果hotItems没有元素, 则当前就是第一个
                    if (!hotItems.iterator().hasNext()) {
                        ctx.timerService().registerEventTimeTimer(hotItem.getWindowEnd() + 5000);
                    
                    }
                    
                    hotItemListState.add(hotItem);
                    
                }
                
                @Override
                public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                    // 排序取topN
                    List<HotItem> list = AtguiguUtil.toList(hotItemListState.get());
                    list.sort((o1, o2) -> o2.getClickCount().compareTo(o1.getClickCount()));
                    
                    StringBuilder sb = new StringBuilder();
                    sb.append("========================\n");
                    for (int i = 0; i < Math.min(3, list.size()); i++) {
                        HotItem hotItem = list.get(i);
                        sb
                            .append("窗口: ")
                            .append(new Date(hotItem.getWindowEnd()))
                            .append(", 商品: ")
                            .append(hotItem)
                            .append("\n");
                    }
                    
                    out.collect(sb.toString());
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
